import React, { useState } from 'react'
import {
  Table,
  Button,
  Space,
  Tag,
  Tooltip,
  Popconfirm,
  Typography,
  Badge,
  Dropdown,
  message,
} from 'antd'
import type { ColumnsType, TableProps } from 'antd/es/table'
import {
  DatabaseOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  StopOutlined,
  MoreOutlined,
  EyeOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons'
import type { Connection } from '@/types/connection'
import { formatDateTime, formatRelativeTime } from '@/utils'

const { Text } = Typography

interface ConnectionListProps {
  connections: Connection[]
  loading?: boolean
  onEdit: (connection: Connection) => void
  onDelete: (id: string) => void
  onTest: (id: string) => void
  onToggleStatus: (id: string, isActive: boolean) => void
  onViewStats: (connection: Connection) => void
  onViewSchema: (connection: Connection) => void
}

const ConnectionList: React.FC<ConnectionListProps> = ({
  connections,
  loading = false,
  onEdit,
  onDelete,
  onTest,
  onToggleStatus,
  onViewStats,
  onViewSchema,
}) => {
  const [testingIds, setTestingIds] = useState<Set<string>>(new Set())

  // 处理连接测试
  const handleTest = async (id: string) => {
    setTestingIds(prev => new Set(prev).add(id))
    try {
      await onTest(id)
    } finally {
      setTestingIds(prev => {
        const newSet = new Set(prev)
        newSet.delete(id)
        return newSet
      })
    }
  }

  // 处理状态切换
  const handleToggleStatus = (connection: Connection) => {
    onToggleStatus(connection.id, !connection.is_active)
  }

  // 获取连接状态
  const getConnectionStatus = (connection: Connection) => {
    if (!connection.is_active) {
      return {
        status: 'disabled',
        color: 'default',
        text: '已禁用',
        icon: <StopOutlined />,
      }
    }

    // 这里可以根据实际的连接健康检查结果来判断状态
    // 现在使用模拟逻辑
    const isHealthy = Math.random() > 0.2 // 80%的连接是健康的
    
    if (isHealthy) {
      return {
        status: 'healthy',
        color: 'success',
        text: '正常',
        icon: <CheckCircleOutlined />,
      }
    } else {
      return {
        status: 'unhealthy',
        color: 'error',
        text: '异常',
        icon: <CloseCircleOutlined />,
      }
    }
  }

  // 表格列定义
  const columns: ColumnsType<Connection> = [
    {
      title: '连接名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string, record: Connection) => (
        <Space>
          <DatabaseOutlined style={{ color: '#1890ff' }} />
          <div>
            <div style={{ fontWeight: 500 }}>{name}</div>
            {record.description && (
              <Text type="secondary" style={{ fontSize: 12 }}>
                {record.description}
              </Text>
            )}
          </div>
        </Space>
      ),
    },
    {
      title: '主机信息',
      key: 'host_info',
      width: 200,
      render: (_, record: Connection) => (
        <div>
          <Text code>{record.host}:{record.port}</Text>
          <br />
          <Text type="secondary" style={{ fontSize: 12 }}>
            用户: {record.username}
          </Text>
          {record.database_name && (
            <>
              <br />
              <Text type="secondary" style={{ fontSize: 12 }}>
                数据库: {record.database_name}
              </Text>
            </>
          )}
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_, record: Connection) => {
        const status = getConnectionStatus(record)
        return (
          <Tooltip title={status.text}>
            <Badge
              status={status.status as any}
              text={
                <Space size={4}>
                  {status.icon}
                  <span>{status.text}</span>
                </Space>
              }
            />
          </Tooltip>
        )
      },
    },
    {
      title: '最后使用',
      dataIndex: 'last_used_at',
      key: 'last_used_at',
      width: 150,
      render: (lastUsedAt: string) => (
        <div>
          {lastUsedAt ? (
            <>
              <div style={{ fontSize: 12 }}>
                {formatRelativeTime(lastUsedAt)}
              </div>
              <Text type="secondary" style={{ fontSize: 11 }}>
                {formatDateTime(lastUsedAt, 'MM-DD HH:mm')}
              </Text>
            </>
          ) : (
            <Text type="secondary">从未使用</Text>
          )}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (createdAt: string) => (
        <div>
          <div style={{ fontSize: 12 }}>
            {formatRelativeTime(createdAt)}
          </div>
          <Text type="secondary" style={{ fontSize: 11 }}>
            {formatDateTime(createdAt, 'MM-DD HH:mm')}
          </Text>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record: Connection) => {
        const isTesting = testingIds.has(record.id)
        
        const menuItems = [
          {
            key: 'stats',
            label: '查看统计',
            icon: <BarChartOutlined />,
            onClick: () => onViewStats(record),
          },
          {
            key: 'schema',
            label: '查看结构',
            icon: <EyeOutlined />,
            onClick: () => onViewSchema(record),
          },
          {
            type: 'divider' as const,
          },
          {
            key: 'toggle',
            label: record.is_active ? '禁用连接' : '启用连接',
            icon: record.is_active ? <StopOutlined /> : <PlayCircleOutlined />,
            onClick: () => handleToggleStatus(record),
          },
        ]

        return (
          <Space size="small">
            <Tooltip title="测试连接">
              <Button
                type="text"
                size="small"
                icon={<PlayCircleOutlined />}
                loading={isTesting}
                onClick={() => handleTest(record.id)}
              />
            </Tooltip>
            
            <Tooltip title="编辑">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => onEdit(record)}
              />
            </Tooltip>
            
            <Popconfirm
              title="确定删除这个连接吗？"
              description="删除后将无法恢复，请确认操作。"
              onConfirm={() => onDelete(record.id)}
              okText="删除"
              cancelText="取消"
              okButtonProps={{ danger: true }}
            >
              <Tooltip title="删除">
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </Popconfirm>
            
            <Dropdown
              menu={{
                items: menuItems,
                onClick: ({ key }) => {
                  const item = menuItems.find(item => item.key === key)
                  if (item && 'onClick' in item) {
                    item.onClick?.()
                  }
                },
              }}
              trigger={['click']}
            >
              <Button
                type="text"
                size="small"
                icon={<MoreOutlined />}
              />
            </Dropdown>
          </Space>
        )
      },
    },
  ]

  const tableProps: TableProps<Connection> = {
    columns,
    dataSource: connections,
    loading,
    rowKey: 'id',
    pagination: {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => 
        `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
      pageSizeOptions: ['10', '20', '50', '100'],
      defaultPageSize: 20,
    },
    scroll: { x: 1000 },
    size: 'middle',
  }

  return <Table {...tableProps} />
}

export default ConnectionList